package com.bankcomm.ui.specialwidget;

import java.util.Calendar;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;

import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.BaseViewCopy;
import com.bankcomm.ui.specialwidget.LPCityChooser.MyLPCityChooser;
import com.bankcomm.util.SecretUtil;
import com.rytong.tools.clienthello.ClientHello;
import com.rytong.tools.crypto.AESCipher;
import com.rytong.tools.crypto.Base64;
import com.rytong.tools.crypto.HMac;
import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.CssStyle;
import com.rytong.tools.utils.Utils;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.text.InputFilter;
import android.text.method.DigitsKeyListener;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

@SuppressWarnings("unused")
public class LPDigitPasswordTextField extends Component {

   	//密码键盘
    private String isNotNull;
    private boolean bPassword = false;
    InputMethodManager inputManager_;
	public static Dialog dlg;
	LPMid mid = LPMid.getInstance();
	
    public String getIsNotNull() {
        return isNotNull == null ? "" : isNotNull;
    }

    public void setIsNotNull(String isNotNull) {
        this.isNotNull = isNotNull;
    }

	
    // input constraint.(only for TextField)
    private static final String ATTRIBUTE_INPUT_CONSTRAINT = "constraint";
    // input max length.(only for TextField)
    private static final String ATTRIBUTE_INPUT_MAXLENG = "maxleng";
    // input min length.(only for TextField)
    private static final String ATTRIBUTE_INPUT_MINLENG = "minleng";

    // 输入框限制输入类型
    final static int InputType_TYPE_CLASS_TEXT = 0;
    final static int InputType_TYPE_TEXT_VARIATION_PASSWORD = InputType_TYPE_CLASS_TEXT + 1;
    final static int InputType_TYPE_NUMBER_FLAG_DECIMAL = InputType_TYPE_TEXT_VARIATION_PASSWORD + 1;
    final static int InputType_TYPE_CLASS_NUMBER = InputType_TYPE_NUMBER_FLAG_DECIMAL + 1;
    final static int InputType_TYPE_CLASS_DATETIME = InputType_TYPE_CLASS_NUMBER + 1;
    final static int InputType_TYPE_CLASS_PHONE = InputType_TYPE_CLASS_DATETIME + 1;
    final static int InputType_TYPE_TEXT_VARIATION_VISIBLE_PASSWORD = InputType_TYPE_CLASS_PHONE + 1;

	private static final int BORDER_INDENT = 2;

    /**
     * Temporary string for inputing.
     */
    private String temp_;

    int inputFieldWidth_;
    
    private String alertStr;

    public String getAlertStr() {
        return alertStr;
    }

    public void setAlertStr(String alertStr) {
        this.alertStr = alertStr;
    }

    public class MyLPDigitPasswordTextField extends EditText implements CompositedComponent {
        private BaseViewCopy bv_;
        public boolean isDateField_;
        private boolean isWindowVisiable_;
        
        private SecretUtil util_;
        int maxSize;
        public String isNeedKeyBoard;
        public String isKeyBoard;
 

    	public MyLPDigitPasswordTextField(Context context, String value) {
            super(context);
            bv_ = (BaseViewCopy) context;
            util_ = new SecretUtil();
            
            maxSize = maxLeng();
            bv_.maxSize = maxSize;
            
            if (maxSize > 0) {
                setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxSize) });
            }
            setFocusable(true);
            setFocusableInTouchMode(true);
            // set content.
            setText(getPropertyByName("value").toString());
            // set constraint.
            setConstraint(getPropertyByName("style"));
            // 产品规定的输入框为单行输入
            setSingleLine();
            
            setAlertStr((String) getPropertyByName("alertName"));
            inputManager_ = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            
            isNeedKeyBoard=(String)getPropertyByName("isRandomPass");
            isKeyBoard = (String)getPropertyByName("isKeyBoard");
            if (null != isKeyBoard && isKeyBoard.length() > 0 && isKeyBoard.equals("true")) {
				bPassword = true;
			}
            
            if(null != isNeedKeyBoard &&!"".equals(isNeedKeyBoard) && isNeedKeyBoard.equalsIgnoreCase("true")){
            	bPassword = true;
            	Thread t= new Thread(new Runnable() {
					
					@Override
					public void run() {
						util_.getRadomKey(mid);
					}
				});
            	if(mid.isNeedGetKey==false){
            		mid.isNeedGetKey=true;
            		t.start() ;
            	} 
            }
        }
    	
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
        }

        /**
         * @param constraints
         */
        void setConstraint(Object constraint) {
            if (null != constraint) {

                String format = (String) constraint;
                int j = format.indexOf(";");
                if (j >= 0) {
                    String front = format.substring(0, j).trim();
                    String last = format.substring(j + 1).trim();
                    if (front.indexOf("-wap-input-format") != -1) {
                        if (front.indexOf("'n'") != -1) {
                            setKeyListener(new DigitsKeyListener(false, true));
                        } else if (front.indexOf("'N'") != -1) {
                            setKeyListener(new DigitsKeyListener(true, false));
                        } 

                    } else if (last.indexOf("-wap-input-format") != -1) {
                        if (last.indexOf("'n'") != -1) {
                            setKeyListener(new DigitsKeyListener(false, true));
                        } else if (last.indexOf("'N'") != -1) {
                            setKeyListener(new DigitsKeyListener(true, false));
                        } 
                    }
                    if (front.indexOf("-wap-input-required") != -1) {
                        if (front.indexOf("'true'") != -1) {
                            setIsNotNull("true");
                        }
                    } else if (last.indexOf("-wap-input-required") != -1) {
                        if (last.indexOf("'true'") != -1) {
                            setIsNotNull("true");
                        }
                    }
                } else {
                    if (format.indexOf("-wap-input-format") != -1) {
                        if (format.indexOf("'n'") != -1) {
                            setKeyListener(new DigitsKeyListener(false, true));
                        } else if (format.indexOf("'N'") != -1) {
                            setKeyListener(new DigitsKeyListener(true, false));
                        } 
                    } else{
                    	if (format.indexOf("-wap-input-required") != -1) {
                        if (format.indexOf("'true'") != -1) {
                            setIsNotNull("true");
                        	}
                    	}
                    }
                }
            }
        }

		@Override
        public boolean dispatchTouchEvent(MotionEvent event) {
			this.requestFocus();
			if(bPassword){
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (bPassword) {
						inputManager_.hideSoftInputFromWindow(
								this.getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);
						if (dlg == null || !dlg.isShowing()) {
							if (this.isEnabled()) {
								MyLPDigitPasswordTextField temp = (MyLPDigitPasswordTextField) realView_;
								if (isKeyBoard.equals("true")) {
									Utils.keyDlg_ = null ;
									((BaseViewCopy)getContext()).maxSize=maxLeng();
									Utils.showInputWindow(bv_, temp, Utils.sc_);
								} else {
									util_.OnCreateInputWindow(bv_, temp, dlg);
								}
							}
						}
					}
				}
				return true;				
			}
			return super.dispatchTouchEvent(event);
        }
    	
    	

        public Component composited() {
            // TODO Auto-generated method stub
            return LPDigitPasswordTextField.this;
        }

        @Override
        protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
            super.onTextChanged(text, start, lengthBefore, lengthAfter);
            // 输入框内容发生变化时要相应更新其属性集合里的?? 若是日期控件则不需要下面操??
            if (!isDateField_ && isWindowVisiable_) {
                setPropertyByName("value", String.valueOf(text) == null ? "" : String.valueOf(text));
            }
            String onchange = getPropertyByName("onchange");
            if (null != onchange && !"".equals(onchange)) {
                onClick(onchange);
            }
        }

        @Override
        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
            if (focused) {
    			if(bPassword){
    				inputManager_.hideSoftInputFromWindow(this.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    			}	
                String onFocus = getPropertyByName("onFocus");
                if (null != onFocus && !"".equals(onFocus)) {
                    onClick(onFocus);
                }
            } else {
                String onBlur = getPropertyByName("onBlur");
                if (null != onBlur && !"".equals(onBlur)) {
                    onClick(onBlur);
                }
            }

            super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }

        @Override
        protected void onWindowVisibilityChanged(int visibility) {
            isWindowVisiable_ = (View.VISIBLE == visibility ? true : false);
            super.onWindowVisibilityChanged(visibility);
        }

    }

    /**
     * 判断??????是密码控件，如果是则设置输入字符不明文显示
     */
    public void isPassWord() {
        // TODO Auto-generated method stub
        String password = (String) getPropertyByName("type");
        if (null != password && password.equals("password")) {
            // 设置输入文字不明文显??
            setTransformationMethod(new PasswordTransformationMethod());
        }
    }

    public String getContentText() {
        // TODO Auto-generated method stub
        MyLPDigitPasswordTextField temp = (MyLPDigitPasswordTextField) realView_;
        Object o = temp.getText();
        if (null != o)
            return o.toString();
        return "";
    }

    /**
     * @param passwordTransformationMethod
     */
    public void setTransformationMethod(PasswordTransformationMethod passwordTransformationMethod) {
        ((MyLPDigitPasswordTextField) realView_).setTransformationMethod(passwordTransformationMethod);

    }

    /*
     * *************************************************************************
     * Set and Get the attributes from XML documents.
     * *************************************************************************
     */
    /**
     * @return
     */
    public int constraint() {
        String sit = getAttribute(ATTRIBUTE_INPUT_CONSTRAINT);
        int constraint = -1;
        try {
            constraint = Integer.parseInt(sit);
        } catch (NumberFormatException e) {
            constraint = -1;
        }
        return constraint;
    }

    /**
     * @return
     */
    public int maxLeng() {
        int maxLength = 0;
        if (null != property_) {
            String maxSize = (String) property_.get("maxleng");
            if (null != maxSize) {
                maxLength = Integer.parseInt(maxSize);
            }
        }
        return maxLength;
    }

    /**
     * @param maxleng
     */
    public void setMaxLeng(int maxleng) {
        String strMaxLeng = String.valueOf(maxleng);
    }

    /**
     * @return
     */
    public int minLeng() {
        String sminleng = (String) property_.get("minleng");
        int minleng = -1;
        try {
            minleng = Integer.parseInt(sminleng);
        } catch (Exception e) {
            minleng = -1;
        }
        return minleng;
    }

    @Override
    public void initRealView(Activity activity, String value) {
        super.initRealView(activity, value);
        realView_ = new MyLPDigitPasswordTextField(activity, value);
        // 设置5像素的左边距
        realView_.setPadding((int) Utils.getScaledValueX(5), 0, 0, 0);
        isPassWord();

    }
 
    private void setText(String value) {
        // TODO Auto-generated method stub
        MyLPDigitPasswordTextField temp = (MyLPDigitPasswordTextField) realView_;
        if (null == value)
            value = "";
        temp.setText(value);
    }
    
    public String getText(){
    	MyLPDigitPasswordTextField temp = (MyLPDigitPasswordTextField) realView_;
    	String str = null;
    	if (temp.getText() != null) {
			str = temp.getText().toString();
		}
    	return str;
    }

    /**
     * 该方法主要用于指定控件的大小\显示颜色\样式??如果服务端没有给定输出样式大小，则要自行计算一个合适的大小应用于该控件 Mould this component with its shape, color, size and
     * so on.
     * 
     * @return
     * @throws Exception
     *             TODO
     */
    public void mouldH() throws Exception {
        super.mouldH();
		if(null == realView_){
			return;
		}
		
		MyLPDigitPasswordTextField mlppt = (MyLPDigitPasswordTextField)realView_;
        // 表示是否有边框，1表示有边框，0表示无边框，无边框的同时也无背景色(0/1)，什么都不写也表示有边框。
        String border = (String) getPropertyByName("border");
        if("".equals(border)){ // 什么都不写，默认有边框。
            BitmapDrawable bitdraw = new BitmapDrawable(makeBack("" , true));
            setBackgroundDrawable(bitdraw);
        }
        String align = getPropertyByName("align");
        if (null != cssStyle_) {
            if (null != cssStyle().content_
                    && cssStyle().content_.indexOf(CssStyle.BGIMAGEURL) < cssStyle().content_
                            .indexOf(CssStyle.BACKGROUNDCOLOR)) {
                String temp = (String) cssStyle_.getProperty(CssStyle.BACKGROUNDCOLOR);
                if (null != temp && !temp.equals("")) {
                	if("1".equals(border)){//有边框时 画背景色
                		BitmapDrawable bitdraw = new BitmapDrawable(makeBack(temp , true));
                		setBackgroundDrawable(bitdraw);
                		realView_.setDrawingCacheBackgroundColor(Color.parseColor(temp));
                    } else if("0".equals(border)){//border为0，不画边框。
                	    BitmapDrawable bitdraw = new BitmapDrawable(makeBack(temp , false));
                	    setBackgroundDrawable(bitdraw);
                        realView_.setDrawingCacheBackgroundColor(Color.parseColor(temp));
                	}
                }

            } else if (null != cssStyle().content_
                    && cssStyle().content_.indexOf(CssStyle.BGIMAGEURL) > cssStyle().content_
                            .indexOf(CssStyle.BACKGROUNDCOLOR)) {
            	setBackgroundDrawableByCssStyle();            
            }
            String alignTemp = cssStyle_.getProperty(CssStyle.TEXTALIGN);
            if (null != alignTemp && !alignTemp.equals(""))
                align = alignTemp;
        }
        if (align.equalsIgnoreCase("right")) {
            setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        } else if (align.equalsIgnoreCase("center")) {
            setGravity(Gravity.CENTER);
        }
        // 设置输入框的提示语言
        mlppt.setHint((CharSequence) getPropertyByName("hold"));
    }
    
    /**
     * border = 1 时画背景
     * border = 0 或 "" 时，画边框(黑色边框，白色背景)
     */
    private Bitmap makeBack(String bgColor , boolean isOnlyBorder) {
        Bitmap result = null;
        // 定义圆角
        float[] radii = new float[8];
        for (int i = 0; i < 8; i++) {
            radii[i] = 5;
        }
        // 建立一个和控件同样大小的bitmap。
        result = Bitmap.createBitmap(width_, height_, Bitmap.Config.ARGB_8888);
        // 建立一张画布。
        Canvas canvas = new Canvas(result); // 并且以后绘制都在这张画布上进行。
        // 设置画笔。
        Paint paint = new Paint();
        paint.setAntiAlias(true); // 画笔抗锯齿。
        // 定义一个画图的路径。
        Path path = new Path();
        
        if(!isOnlyBorder){
            paint.setColor(Color.parseColor(bgColor));
        } else {
        	// 定义渲染样式
    		LinearGradient bgLg = new LinearGradient(Utils.getScaledValueX(1), 
    				Utils.getScaledValueY(3), Utils.getScaledValueX(1), 
    				height_ - Utils.getScaledValueY(4),
    				new int[] { 0xffededed, Color.WHITE }, null, TileMode.CLAMP);
    		paint.setShader(bgLg);
            path.addRoundRect(new RectF(Utils.getScaledValueX(1),
            		Utils.getScaledValueY(3), width_ - Utils.getScaledValueX(1),
            		height_ - Utils.getScaledValueY(4)), radii,
                    Path.Direction.CW); // 设置绘制路径。
            canvas.drawPath(path, paint);
            
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.STROKE); // 设置空心。
            paint.setStrokeWidth(0.5f); // 设置画笔粗细。
        }
        // 画边线。
        // 定义渲染样式
		LinearGradient borderLg = new LinearGradient(Utils.getScaledValueX(1),
				Utils.getScaledValueY(3), Utils.getScaledValueX(1), 
				height_ - Utils.getScaledValueY(4),
				new int[] { Color.BLACK, 0xffb5b5b5 }, null, TileMode.CLAMP);
		paint.setShader(borderLg);
        path.addRoundRect(new RectF(Utils.getScaledValueX(1), 
        		Utils.getScaledValueY(3), width_ - Utils.getScaledValueX(1),
        		height_ - Utils.getScaledValueY(4)), radii,
                Path.Direction.CW); // 设置绘制路径。
        canvas.drawPath(path, paint); // 绘制边框。
        return result;
    }
}
